﻿
namespace HSS.Xaml.UI.Controls
{
	#region Using Directives
	using System.Windows;
	using System.Windows.Controls;
	#endregion

	#region TextBoxWithToolTip
	/// <summary>
	/// A TextBox that shows a tooltip when hovered and the text exceeds the width
	/// </summary>
	[TemplateVisualState(GroupName = TextBoxWithToolTip.TextTooLongStates, Name = TextBoxWithToolTip.TooLongState)]
	[TemplateVisualState(GroupName = TextBoxWithToolTip.TextTooLongStates, Name = TextBoxWithToolTip.NotTooLongState)]
	public class TextBoxWithToolTip : TextBox
	{
		#region Template
		/// <summary>
		/// The TextTooLongStates hides or make available a ToolTip to expose
		/// the text that exceeds the width of the textbox
		/// </summary>
		public const string TextTooLongStates = "TextTooLongStates";
		/// <summary>
		/// The TooLong state
		/// </summary>
		public const string TooLongState = "TooLong";
		/// <summary>
		/// The NotTooLong state
		/// </summary>
		public const string NotTooLongState = "NotTooLong";
		#endregion

		#region Constructors
		/// <summary>
		/// Constructor
		/// </summary>
		public TextBoxWithToolTip()
		{
			this.DefaultStyleKey = typeof(TextBoxWithToolTip);
			this.Loaded += (s, e) =>
			{
				this.SizeChanged += (s1, e1) => { MeasureText(); };
				this.TextChanged += (s2, e2) => { MeasureText(); };
				this.MeasureText();
			};
		}
		#endregion

		#region Methods
		void MeasureText()
		{
			// Measure text length and compares to TextBox Viewport and goes to the 
			// appropriate state of setting the Tooltip Visible or Collapsed.
			// NOTE: does not open or close the tooltip, just makes it available
			var size = this.Text.Measure(this.FontSize, this.FontFamily, this.FontWeight);
			bool isTextTooLong = (size.Width > this.ActualWidth);
			if (isTextTooLong)
				VisualStateManager.GoToState(this, TooLongState, false);
			else
				VisualStateManager.GoToState(this, NotTooLongState, false);
		}
		#endregion
	}
	#endregion
}
